package com.ys.service.purchase.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.base.CheckByGrid;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.flow.YspModel;
import com.ys.entity.purchase.TcgPurchaseAppointOrderProductComponent;
import com.ys.entity.purchase.TcgPurchaseContract;
import com.ys.entity.purchase.TcgPurchaseContractItem;
import com.ys.entity.sys.*;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.product.ProductMapper;
import com.ys.mapper.purchase.TcgPurchaseAppointOrderProductComponentMapper;
import com.ys.mapper.purchase.TcgPurchaseContractItemMapper;
import com.ys.mapper.purchase.TcgPurchaseContractMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchaseContractService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.*;

/**
 * 采购合同单
 */
@Service("tcgPurchaseContractService")
public class TcgPurchaseContractServiceImpl implements TcgPurchaseContractService {
	private static final Logger logger = LoggerFactory.getLogger(TcgPurchaseContractServiceImpl.class);

	@Autowired
	private TcgPurchaseContractMapper tcgPurchaseContractMapper;

	@Autowired
	private TcgPurchaseContractItemMapper tcgPurchaseContractItemMapper;

	@Autowired
	private TcgPurchaseAppointOrderProductComponentMapper tcgPurchaseAppointOrderProductComponentMapper;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

	private final Long GRID = 47L;

	/**
	 * 新增
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("新增传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcgPurchaseContract entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchaseContract.class);
		entity.setStatus(1);//状态
		entity.setEffectStock(0);//审批状态
		entity.setContractFile("0个附件");

		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
		if(tsUserChange!=null){
			entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			return R.error("未查询到制单人信息！");
		}

		//保存列表信息
		R saveItemRes = saveItem(params,entity);
		if(saveItemRes.getCode()==1){
			return saveItemRes;
		}

		//新增
		tcgPurchaseContractMapper.insert(entity);

		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, entity.getBid(), createUserId);
		}
		//return R.ok(EditDto.closeAndReload());
		return R.ok(AddDto.gotoEdit("/web/purchase/tcgPurchaseContract/toEdit?bid=" + entity.getBid()));
	}


	/**
	 * 修改
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcgPurchaseContract entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchaseContract.class);
		// 验证状态
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst == null) {
			return R.error("审批数据不存在，无法编辑");
		} else if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("已流转，无法编辑");
		}

		//保存列表信息
		R saveItemRes = saveItem(params,entity);
		if(saveItemRes.getCode()==1){
			return saveItemRes;
		}
		tcgPurchaseContractMapper.update(entity);
		return R.ok();
	}


	//保存子列表信息
	public R saveItem(Map<String, Object> params, TcgPurchaseContract entity) throws Exception{
		//保存列表信息
		List<Map<String, Object>> subDataList = new ArrayList<>();
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			CheckByGrid checkByGrid = checkParamsByGrid(subData,GRID,params);
			if(checkUtil.isNotNullByObject(checkByGrid.getErrMsg())){
				return R.error(checkByGrid.getErrMsg());
			}
			subDataList = checkByGrid.getSubDataList();
		}else {
			return R.error("列表信息为空！");
		}

		//先删除采购合同详情数据
		productMapper.deleteTcgPurchaseContractItemByPbid(entity.getBid());
		//再新增
		for (int i = 0; i < subDataList.size(); i++) {
			Map<String, Object> item = subDataList.get(i);
			TcgPurchaseContractItem itemInfo = JSON.parseObject(JSON.toJSONString(item), TcgPurchaseContractItem.class);
			itemInfo.setStatus(1);
			itemInfo.setPbid(entity.getBid());
			//新增
			tcgPurchaseContractItemMapper.insert(itemInfo);
		}
		return R.ok();
	}


	//删除
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R del(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		TcgPurchaseContract entity = new TcgPurchaseContract().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		if (!tsUserChange.getUserId().equals(loginUserId) && !"admin".equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		//删除
		tcgPurchaseContractMapper.deleteTrue(id);
		//删除列表信息
		productMapper.deleteTcgPurchaseContractItemByPbid(entity.getBid());
		//删除流程
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}


	//根据主表bid获取子表信息
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public List<Map<String,Object>> getItemListByBid(String bid) throws Exception {
		//获取子表信息
		List<Map<String,Object>> itemList = new TcgPurchaseContractItem()
				//.addField("A.SubBomNumber AS subBomNumber")//子件BOM数量
				//.addField("A.SubPurchaseNum AS subPurchaseNum")//子件采购数量
				//.addField("A.SubPurchasePrice AS subPurchasePrice")//子件采购单价
				//.addField("A.PurchaseTotalPrice AS purchaseTotalPrice")//子件采购总价

				.addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Id = A.OrderProductComponentId")//预约采购管理子件表
				.addLeftJoin("TCG_PurchaseAppointOrderItem PC ON C.Pid = PC.Id")//预约采购管理母件表
				.addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PC.Pbid")//预约采购单母表
				.addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表

				.addLeftJoin("TB_CompanyInfo CI ON CI.Vid = PPC.CompanyVid ")//公司信息
				.addField("CI.Vname AS vname")//购买方公司名称

				.addField("PPC.Id AS purchaseAppointOrderId")//预约采购管理表id
				.addField("PPC.Bid AS appointOrderBid")//预约采购单单号
				.addField("PPC.Vgsbm AS vgsbm")//运营公司编码
				.addField("OCA.Vgsjc AS vgsjc")//运营公司简称
				.addField("PC.ProductCode AS productCode")//商品编码
				.addField("PC.ProductName AS productName")//商品名称
				.addField("PC.CodeMerge AS codeMerge")//合并商品编码
				.addField("PC.ReserveNumber AS reserveNumber")//母件预约数量
				.addField("C.SubCode AS subCode")//子件编码
				.addField("C.SubName AS subName")//子件名称
				.addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码
				.addField("C.SubReserveNumber AS subReserveNumber")//子件预约数量
				.addField("C.SubTotalPrice AS subTotalPrice")//子件总价

				.setPbid(bid)
				.queryMap();
		return  itemList;
	}


	/**
	 * 流转通过
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowPass(String bid,String userId) throws Exception {
		//获取单据信息
		TcgPurchaseContract entity = new TcgPurchaseContract().setBid(bid).queryFirst();
		if (entity == null) {
			return R.error("该单据不存在,请核实后再操作!");
		}

		//获取子表信息
		List<Map<String,Object>> itemList = getItemListByBid(bid);

		if(itemList == null || itemList.size()<=0){
			return R.error("该单据列表不存在,请核实后再操作!");
		}

		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();

		// 若流程是初始化状态，需要验证账户金额
		if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
			String errorMsg = null;

			for(Map<String,Object> item:itemList){
				if(checkUtil.isNotNullByObject(item.get("vgsbm"))){
					//获取公司编码
					String vGsBm = item.get("vgsbm").toString();
					//根据公司编码获取对应的实时资金表信息
					TcwAccountCountForCompany account = new TcwAccountCountForCompany().setVGsBm(vGsBm).queryFirst();
					//获取对应的实时资金信息
					BigDecimal amountAble = account.getFJe().add(account.getFFzEd()).subtract(account.getFDjJe());
					//判断金额是否大于公司的实时资金
					if (amountAble.compareTo(new BigDecimal(item.get("purchaseTotalPrice").toString()).negate()) < 0) {
						errorMsg = "【" + vGsBm + "】账户可用余额不足，无法流转";
					}
				}
			}
			if(checkUtil.isNotNullByObject(errorMsg)){
				return R.error(errorMsg);
			}
		}

		Flow f = yspTaskService.flowPass(entity.getBid(),userId);

		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			// 若是制单流转，冻结账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				frozenOrThawByList(itemList,1,"subTotalPrice");//解冻
				frozenOrThawByList(itemList,0,"purchaseTotalPrice");//冻结
			}
			if (f.getState() == Flow.State.FINISH.value) {
				flowFinish(entity,itemList);
			}
			return R.ok();
		}
	}

	/**
	 * 流转结束
	 */
	public void flowFinish(TcgPurchaseContract entity,List<Map<String,Object>> itemList) throws Exception {

		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setUpdateTime(theDate);

		//****1、解冻****
		frozenOrThawByList(itemList,1,"purchaseTotalPrice");//解冻

		//遍历详情信息
		for (Map<String,Object> item : itemList){

			BigDecimal purchaseTotalPrice = new BigDecimal(item.get("purchaseTotalPrice").toString());

			String vgsbm = item.get("vgsbm").toString();
			String vgsjc = item.get("vgsjc").toString();

			String subCode = item.get("subCode")!=null ? item.get("subCode").toString() : "";//子件编码
			String subName = item.get("subName")!=null ? item.get("subName").toString() : "";//子件名称

			String subPurchaseNum = item.get("subPurchaseNum").toString();//子件采购数量

			//****2、新增流水****
			//必填：vgsbm划出公司编码；vgsbmp划入公司编码；vjylx交易类型；fje交易金额；djysj交易时间；dshsj审核时间；vbz备注
			//选填：mname;mtype;mnid;mbid;mguid；writeTime记账时间（如果为空，默认审核时间）
			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
					vgsbm,vgsjc,"GS0607","采购部",
					"采购服务→采购成本", purchaseTotalPrice.negate(),entity.getCreateTime(), theDate,
					"采购合同单："+entity.getBid()+"，"+subCode+"-"+subName+"-"+subPurchaseNum+"，"+(entity.getRemark()!=null ? entity.getRemark():""),
					entity.getBid(),theDate);

			tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
					"GS0607","采购部",vgsbm,vgsjc,
					"采购服务→采购成本", purchaseTotalPrice,entity.getCreateTime(), theDate,
					"采购合同单："+entity.getBid()+"，"+subCode+"-"+subName+"-"+subPurchaseNum+"，"+(entity.getRemark()!=null ? entity.getRemark():""),
					entity.getBid(),theDate);

			//****3、填入管理表单数据****
			TcgPurchaseContractItem sonInfo = new TcgPurchaseContractItem();
			sonInfo.setId(Long.parseLong(item.get("id").toString()));
			sonInfo.setSubPaymentNum(0);//子件付款数量
			sonInfo.setSubWarehousingNum(0);//子件入库数量
			sonInfo.setSubWriteOffNum(0);//子件核销数量
			sonInfo.setSubPreWarehousingNum(0);
			sonInfo.setSubPaymentState(0);//采购付款完整性（0否、1是）
			sonInfo.setSubWarehousingState(0);//采购入库完整性（0否、1是）
			sonInfo.setSubWriteOffState(0);//采购核销完整性（0否、1是）
			sonInfo.setCancelState(1);//采购取消状态（0取消、1正常）
			tcgPurchaseContractItemMapper.update(sonInfo);

			//****4、回填预约采购管理-预约采购完整性****
			TcgPurchaseAppointOrderProductComponent tcgPurchaseAppointOrderProductComponent = new TcgPurchaseAppointOrderProductComponent();
			tcgPurchaseAppointOrderProductComponent.setId(Long.parseLong(item.get("orderProductComponentId").toString()));
			tcgPurchaseAppointOrderProductComponent.setStateAppointPurchase(1);//修改完整性-0否1是
			tcgPurchaseAppointOrderProductComponent.setSubPurchaseNumber(Integer.parseInt(subPurchaseNum));//子件采购数量
			tcgPurchaseAppointOrderProductComponentMapper.update(tcgPurchaseAppointOrderProductComponent);
		}

		//修改信息
		tcgPurchaseContractMapper.update(entity);

	}

	//流转驳回
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowRefuse(String bid, String reason,String userId) throws Exception{

		R r = yspTaskService.flowRefuse(bid, reason, userId);

		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				//获取子表信息
				List<Map<String,Object>> itemList = getItemListByBid(bid);
				frozenOrThawByList(itemList,0,"subTotalPrice");//冻结
				frozenOrThawByList(itemList,1,"purchaseTotalPrice");//解冻
			}
		}
		return r;
	}


	//采购取消
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R cancelInfo(String bid) throws Exception{

		//List<Map<String,Object>> itemList = getItemListByBid(bid);
		//获取子表信息
		List<Map<String,Object>> itemList = new TcgPurchaseContractItem()
				.addLeftJoin("TCG_PurchaseAppointOrderProductComponent C ON C.Id = A.OrderProductComponentId")//预约采购管理子件表
				.addLeftJoin("TCG_PurchaseAppointOrderItem PC ON C.Pid = PC.Id")//预约采购管理母件表
				.addLeftJoin("TCG_PurchaseAppointOrder PPC ON PPC.Bid = PC.Pbid")//预约采购单母表
				.addLeftJoin("THR_OperateCompanyApply OCA ON OCA.Vgsbm = PPC.Vgsbm")//运营公司管理表
				.addField("PPC.Id AS purchaseAppointOrderId")//预约采购管理表id
				.addField("PPC.Bid AS appointOrderBid")//预约采购单单号
				.addField("PPC.Vgsbm AS vgsbm")//运营公司编码
				.addField("OCA.Vgsjc AS vgsjc")//运营公司简称
				.addField("PC.ProductCode AS productCode")//商品编码
				.addField("PC.ProductName AS productName")//商品名称
				.addField("PC.CodeMerge AS codeMerge")//合并商品编码
				.addField("PC.ReserveNumber AS reserveNumber")//母件预约数量
				.addField("C.SubCode AS subCode")//子件编码
				.addField("C.SubName AS subName")//子件名称
				.addField("C.SubCodeMerge AS subCodeMerge")//子件合并编码
				.addField("C.SubReserveNumber AS subReserveNumber")//子件预约数量

				.setCancelState(1)//采购取消状态

				.setPbid(bid)
				.queryMap();

		if(itemList!=null && itemList.size()>0){
			for(Map<String,Object> item : itemList){
				TcgPurchaseContract entity = new TcgPurchaseContract().setBid(item.get("pbid").toString()).queryFirst();
				YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();

				//验证是否：子件存在付款数量、入库数量、核销数量
				String checkMsg = "";
				int subPaymentNum = item.get("subPaymentNum")!=null?Integer.parseInt(item.get("subPaymentNum").toString()):0;//付款数量
				int subWarehousingNum = item.get("subWarehousingNum")!=null?Integer.parseInt(item.get("subWarehousingNum").toString()):0;//入库数量
				int subWriteOffNum = item.get("subWriteOffNum")!=null?Integer.parseInt(item.get("subWriteOffNum").toString()):0;//核销数量
				int subPreWarehousingNum = item.get("subPreWarehousingNum")!=null?Integer.parseInt(item.get("subPreWarehousingNum").toString()):0;//预入库数量
				if(subPaymentNum!=0 || subWarehousingNum!=0 || subWriteOffNum!=0|| subPreWarehousingNum!=0){
					checkMsg = "子件："+item.get("subCode")+"，存在付款数量、预入库数量、入库数量、核销数量";
				}
				if(checkUtil.isNotNullByObject(checkMsg)){
					//return R.error(checkMsg);
					throw new IllegalArgumentException(checkMsg);
				}

				//取消
				String vgsbm = item.get("vgsbm").toString();
				String vgsjc = item.get("vgsjc").toString();
				String subCode = item.get("subCode")!=null ? item.get("subCode").toString() : "";//子件编码
				String subName = item.get("subName")!=null ? item.get("subName").toString() : "";//子件名称
				BigDecimal purchaseTotalPrice = new BigDecimal(item.get("purchaseTotalPrice").toString());
				String subPurchaseNum = item.get("subPurchaseNum").toString();//子件采购数量
				Date theDate = ysProcInst.getUpdateTime();//审核时间

				//1、流水退回
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						vgsbm,vgsjc,"GS0607","采购部",
						"采购服务→采购成本", purchaseTotalPrice,entity.getCreateTime(), theDate,
						"采购合同单取消："+entity.getBid()+"，"+subCode+"-"+subName+"-"+subPurchaseNum+"，"+(entity.getRemark()!=null ? entity.getRemark():""),
						entity.getBid(),theDate);

				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						"GS0607","采购部",vgsbm,vgsjc,
						"采购服务→采购成本", purchaseTotalPrice.negate(),entity.getCreateTime(), theDate,
						"采购合同单取消："+entity.getBid()+"，"+subCode+"-"+subName+"-"+subPurchaseNum+"，"+(entity.getRemark()!=null ? entity.getRemark():""),
						entity.getBid(),theDate);

				//2、修改状态
				TcgPurchaseContractItem sonInfo = new TcgPurchaseContractItem();
				sonInfo.setId(Long.parseLong(item.get("id").toString()));
				sonInfo.setCancelState(0);//采购取消状态（0取消、1正常）
				tcgPurchaseContractItemMapper.update(sonInfo);

				//3、回填预约采购管理-预约采购完整性
				TcgPurchaseAppointOrderProductComponent tcgPurchaseAppointOrderProductComponent = new TcgPurchaseAppointOrderProductComponent();
				tcgPurchaseAppointOrderProductComponent.setId(Long.parseLong(item.get("orderProductComponentId").toString()));
				tcgPurchaseAppointOrderProductComponent.setStateAppointPurchase(0);//修改完整性-0否1是
				tcgPurchaseAppointOrderProductComponent.setSubPurchaseNumber(0);//子件采购数量
				tcgPurchaseAppointOrderProductComponentMapper.update(tcgPurchaseAppointOrderProductComponent);
			}

		} else {
			return R.error("未查询到要取消的采购合同管理信息！");
		}

		return R.ok();
	}


	//流转退回
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowInit(String bid, String reason,String userId) throws Exception{
		R r = yspTaskService.flowInit(bid, reason, userId);
		if (r.getCode() == R.Code.SUCCESS.value) {
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			// 若退回到制单状态，则解冻账户
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				//获取子表信息
				List<Map<String,Object>> itemList = getItemListByBid(bid);
				frozenOrThawByList(itemList,0,"subTotalPrice");//冻结
				frozenOrThawByList(itemList,1,"purchaseTotalPrice");//解冻
			}
		}
		return r;
	}

	//根据子表信息，冻结、解冻
	//frozenOrThaw 0冻结 ,1解冻
	//subTotalPrice 子件总价 ；purchaseTotalPrice 子件采购总价
	public void frozenOrThawByList(List<Map<String,Object>> itemList,int frozenOrThaw,String code) throws Exception{
		if(itemList!=null && itemList.size()>0) {
			for (Map<String, Object> item : itemList) {
				if (checkUtil.isNotNullByObject(item.get("vgsbm"))) {
					if(frozenOrThaw == 0){
						//冻结
						tcwAccountCountForCompanyService.frozen(item.get("vgsbm").toString(), new BigDecimal(item.get(code).toString()),
								TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseContract.value,
								Long.parseLong(item.get("id").toString()),
								item.get("pbid").toString(),
								null);
					}else {
						//解冻
						tcwAccountCountForCompanyService.thaw(item.get("vgsbm").toString(), new BigDecimal(item.get(code).toString()),
								TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseContract.value,
								Long.parseLong(item.get("id").toString()),
								item.get("pbid").toString(),
								null);
					}
				}
			}
		}
	}

	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCG_PurchaseContract",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		if(checkUtil.isNotNullByObject(params.get("companyVname")) && checkUtil.isNotNullByObject(params.get("vname"))){
			if (!params.get("companyVname").toString().equals(params.get("vname").toString())){
				backMsg = "\"购买方公司名称\"必须和\"付款户名\"的\"所属公司\"一致";
			}
		}

		return backMsg;
	}


	/**
	 * 子表参数验证
	 */
	public CheckByGrid checkParamsByGrid(JSONArray subDataArray, Long gridId,Map<String, Object> params) throws Exception {
		CheckByGrid checkByGrid = new CheckByGrid();
		//获取pc字段数据
		List<YsGridCol> listField = new YsGridCol()
				.setGridId(gridId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		String backMsg = "";
		List<Map<String, Object>> subDataList = new ArrayList<>();

		if(subDataArray!=null && subDataArray.size()>0){
			for (int i = 0; i < subDataArray.size(); i++) {
				JSONObject jsonObject = subDataArray.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				for (String key : jsonObject.keySet()) {
					paramsNewByRecord.put(key, jsonObject.get(key));
				}
				subDataList.add(paramsNewByRecord);
			}
			//验证
			for(int i = 0;i<subDataList.size();i++){
				String backMsgByRow = "";
				Map<String, Object> subData = subDataList.get(i);
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsgByRow += checkUtil.checkTableColLengthAndDataTypeByGrid(
						"TCG_PurchaseContractItem",
						listField,
						subData,
						ysColItem->
								ysColItem.getCode().equals("appointOrderId")
								|| ysColItem.getCode().equals("subPurchaseNum")
										|| ysColItem.getCode().equals("subPurchasePrice")
										|| ysColItem.getCode().equals("purchaseTotalPrice")
										|| ysColItem.getCode().equals("subBomNumber")
				);
				if(checkUtil.isNotNullByObject(subData.get("vname")) && checkUtil.isNotNullByObject(params.get("vname"))){
					if(!subData.get("vname").toString().equals(params.get("vname").toString())){
						backMsgByRow += "该子表数据所在的购买方公司名称应与母表一致；";
					}
				}
				if(checkUtil.isNotNullByObject(backMsgByRow)){
					backMsg += "列表第" + (i+1) + "行，" + backMsgByRow;
				}
			}
		}else{
			backMsg = "列表信息为空";
		}
		checkByGrid.setErrMsg(backMsg);
		checkByGrid.setSubDataList(subDataList);

		return checkByGrid;
	}

	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String,Object> extraParam = new TcgPurchaseContract()

				.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
				.addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

				//.addLeftJoin("TCG_PurchaseAppointOrder O ON O.Id = A.PurchaseAppointOrderId ")//预约采购管理表
				.addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyInfoVid ")//公司信息
				.addField("CI.Vname AS vname")//购买方公司名称
				.addField("CI.Tax AS tax")//公司税号

				.addLeftJoin("TB_CompanyBankInfo B ON B.Id = A.CompanyBankInfoId ")//公司银行账户管理表
				.addField("B.Vyhzhmc AS vyhzhmc")//付款户名 、 银行账户名称
				.addField("B.Vkhh AS vkhh")//付款银行 、 开户行
				.addField("B.Vyhzh AS vyhzh")//付款银行账户 、 银行账户编码

				.addLeftJoin("TB_CompanyInfo BCI ON  BCI.Vid = B.CompanyInfoVid")
				.addField("BCI.Vname companyVname")//付款所属公司名称

				.addLeftJoin("TCW_PartnerBankInfo PB ON PB.Id = A.PartnerBankInfoId ")//合作商银行账户管理表
				.addField("PB.PartnerName AS partnerName")//供应方公司名称 、合作方名称
				.addField("PB.Vgssh AS vgssh")//供应方公司税号 、 合作方税号
				.addField("(PB.Vlxr + '&' +  PB.Vgsdh) AS vgsdh")//联系人及方式 、 联系人&联系方式
				.addField("PB.Vyhzhmc AS pbVyhzhmc")//收款户名 、 银行账户名称
				.addField("PB.Vkhh AS pbVkhh")//收款银行 、 开户行
				.addField("PB.Vyhzh AS pbVyhzh")//收款银行账户 、 银行账户编码

				.setBid(bid)
				.queryFirstMap();
		return extraParam;
	}


}
